package satir.card;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Stack;

import satir.framework.LazyInitiator;

/**
 * The Class Deck act as a container of cards.
 * @version 3.0 April 2012
 * @author Creative Family
 */
public class Deck {

    /** The cards. */
    private Stack<Card> cards;

    /** The drawed cards. */
    private ArrayList<Card> drawedCards;

    /**
     * Instantiates a new deck.
     */
    public Deck() {
	cards = new Stack<Card>();
	drawedCards = new ArrayList<Card>();
    }

    /**
     * Load card by using LazyInitiator. Will create a set of card according to
     * the cardKey
     * @param cardType
     *            the card type
     * @param cardKeys
     *            the card keys
     */
    public void loadCard(final String cardType, final String[] cardKeys) {
	for (int i = 0; i < cardKeys.length; i++) {
	    cards.push((Card) LazyInitiator.get(cardType, cardKeys[i]));
	}
	shuffle();
    }

    /**
     * Draw card.
     * @return the card on the top
     */
    public Card drawCard() {
	if (cards.isEmpty()) {
	    restoreDeck();
	}
	shuffle();
	Card card = cards.pop();
	drawedCards.add(card);
	return card;
    }

    /**
     * Gets the size.
     * @return the size
     */
    public int getSize() {
	return cards.size();
    }

    /**
     * Shuffle the card in deck.
     */
    private void shuffle() {
	Collections.shuffle(cards);
    }

    /**
     * Put back all card in the deck.
     */
    private void restoreDeck() {
	for (int i = 0; i < drawedCards.size(); i++) {
	    cards.push(drawedCards.get(i));
	}
	drawedCards = new ArrayList<Card>();
    }
}
